package com.rizzo.android.ui;

import android.accounts.Account;
import android.accounts.AccountAuthenticatorActivity;
import android.accounts.AccountManager;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import com.rizzo.android.content.RizzoContent;

public class AuthenticatorActivity extends AccountAuthenticatorActivity {

    public static final String PARAM_ACCOUNT_TYPE = "com.rizzo.android";
    public static final String PARAM_AUTHTOKEN_TYPE = "authtokenType";
    public static final String PARAM_USERNAME = "username";
    public static final String PARAM_PASSWORD = "password";
    public static final String PARAM_CONFIRMCREDENTIALS = "confirmCredentials";

    private AccountManager accountManager;
    private Thread authThread;
    private String authToken;
    private String authTokenType;
    private Boolean confirmCredentials = false;
    private final Handler handler = new Handler();
    protected boolean requestNewAccount = false;

    private String username;
    private String password;

    private TextView message;
    private EditText passwordEdit;
    private EditText usernameEdit;

    @Override
    protected void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        this.accountManager = AccountManager.get(this);
        Log.i(this.getClass().getCanonicalName(), "Loading data from Intent...");
        final Intent intent = getIntent();
        this.username = intent.getStringExtra(PARAM_USERNAME);
        this.authTokenType = intent.getStringExtra(PARAM_AUTHTOKEN_TYPE);
        this.requestNewAccount = username == null;
        this.confirmCredentials = intent.getBooleanExtra(PARAM_CONFIRMCREDENTIALS, false);

//		  message = (TextView) findViewById(R.id.message);
//        usernameEdit = (EditText) findViewById(R.id.username_edit);
//        passwordEdit = (EditText) findViewById(R.id.password_edit);

        usernameEdit.setText(username);
        message.setText(getMessage());
    }

    /*
     * {@inheritDoc}
     */
    @Override
    protected Dialog onCreateDialog(int id, Bundle args) {
        final ProgressDialog dialog = new ProgressDialog(this);
        dialog.setMessage(getText(0));//R.string.ui_activity_authenticating));
        dialog.setIndeterminate(true);
        dialog.setCancelable(true);
        dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
            public void onCancel(DialogInterface dialog) {
                Log.i(this.getClass().getCanonicalName(), "Dialog cancel has been invoked");
                if (authThread != null) {
                    authThread.interrupt();
                    finish();
                }
            }
        });
        return dialog;
    }

    private void handleLogin(View view) {
        String username = null;
        if (this.requestNewAccount) {
            username = usernameEdit.getText().toString();
        }
        this.password = passwordEdit.getText().toString();
        if (TextUtils.isEmpty(username) || TextUtils.isEmpty(password)) {
            message.setText(getMessage());
        }
        showProgress();
//		this.authThread = NetworkUtilities.attemptAuth(username,
//				this.password, this.handler, AuthenticatorActivity.this);
    }

    public void onAuthenticationResult(Boolean result) {
//		hideProgress();
        if (result) {
            if (!confirmCredentials) {
                finishLogin();
            }
        } else {
            message.setText("User and/or password are incorrect");
        }
    }

    private void finishLogin() {
        final Account account = new Account(this.username, PARAM_ACCOUNT_TYPE);
        if (requestNewAccount) {
            accountManager.addAccountExplicitly(account, this.password, null);
            updateSyncSettings(account);
        } else {
            accountManager.setPassword(account, this.password);
        }
        final Intent intent = new Intent();
        intent.putExtra(AccountManager.KEY_ACCOUNT_NAME, this.username);
        intent.putExtra(AccountManager.KEY_ACCOUNT_TYPE, PARAM_ACCOUNT_TYPE);

        if (authTokenType != null && authTokenType.equals(PARAM_AUTHTOKEN_TYPE)) {
            // TODO is it token or password here?
            intent.putExtra(AccountManager.KEY_AUTHTOKEN, authToken);
        }
        setAccountAuthenticatorResult(intent.getExtras());
        setResult(RESULT_OK, intent);
        finish();
    }

    private void updateSyncSettings(Account account) {
        Bundle params = new Bundle();
        params.putBoolean(ContentResolver.SYNC_EXTRAS_EXPEDITED, false);
        params.putBoolean(ContentResolver.SYNC_EXTRAS_DO_NOT_RETRY, false);
        params.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, false);
        ContentResolver.addPeriodicSync(account, RizzoContent.AUTHORITY, params, 30);
        ContentResolver.setSyncAutomatically(account, RizzoContent.AUTHORITY, true);
        ContentResolver.requestSync(account, RizzoContent.AUTHORITY, params);
    }

    /**
     * Returns the message to be displayed at the top of the login dialog box.
     */
    private CharSequence getMessage() {
//        getString(R.string.label);
        if (TextUtils.isEmpty(username)) {
            // If no username, then we ask the user to log in using an
            // appropriate service.
            final CharSequence msg = "";
//                getText(R.string.login_activity_newaccount_text);
            return msg;
        }
        if (TextUtils.isEmpty(password)) {
            // We have an account but no password
//            return getText(R.string.login_activity_loginfail_text_pwmissing);
        }
        return null;
    }

    /**
     * Shows the progress UI for a lengthy operation.
     */
    protected void showProgress() {
        showDialog(0);
    }

}
